package dawn.jxufe.community.service;

import dawn.jxufe.community.dao.CommentMapper;
import dawn.jxufe.community.entity.Comment;
import dawn.jxufe.community.util.CommunityConstant;
import dawn.jxufe.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

/**
 * @author dawn21
 * @version 1.0
 * @date 2022/7/30 11:02
 * @component
 */
@Service
public class CommentService implements CommunityConstant {
    @Autowired
    private CommentMapper commentMapper;

    // 敏感词过滤组件注入。
    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private DiscussPostService discussPostService;

    public List<Comment> findCommentsByEntity(int entityType, int entityId, int offset, int limit){
        return commentMapper.selectCommentsByEntity(entityType, entityId, offset, limit);
    }

    public int findCommentsCount(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    // 处理增加评论的业务(核心)，一次业务会修改两次数据库，需要事务管理。以便发生异常时都可以回滚。
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment) { // 对评论内容的过滤，包括标签和敏感词。
        if (comment == null) {
            throw new IllegalArgumentException("评论为空！");
        }

        // 添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent())); // 过滤标签
        comment.setContent(sensitiveFilter.filter(comment.getContent())); // 过滤敏感词
        int rows = commentMapper.insertComment(comment);

        // 更新帖子评论条数。
        if (comment.getEntityType() == ENTITY_TYPE_POST) { // 是帖子评论。
            int count = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(), count);
        }

       return rows;
    }

    public Comment findCommentById(int id) {
        return commentMapper.selectCommentById(id);
    }

    public List<Comment> findUserComments(int userId, int offset, int limit) {
        return commentMapper.selectCommentsByUser(userId, offset, limit);
    }

    public int findUserCount(int userId) {
        return commentMapper.selectCountByUser(userId);
    }


}
